import grails.converters.JSON
import grails.converters.deep.XML
import org.codehaus.groovy.grails.commons.ConfigurationHolder

class MassLookupController {

  /**
   * does the actual converting of data
   */
  ConvertService convertService
  DataExportService dataExportService = new DataExportService();

  def index =
  {
    String ids = ""
    String from = params.from
    def to = params.to


    if( session.getAttribute("ids") != null )
    {
      ids = session.getAttribute("ids").toString()
    }

    if(params.from != null)
    {
      from = params.from
    }

    if(params.to != null)
    {
      to = params.to
    }

    return [fromFields:convertService.getFromConversions(),toFields:convertService.toConversions,ids:ids,from:from,to:to]
  }

  /**
   * process list of ids and returns a map containning all the found Compounds 
   */
  def masstransform =
  {

    String from = params.from
    def StrTo = params.to
    String ids = ""


    if( params.ids != null )
    {
       ids = params.ids
       session.setAttribute("ids",ids);
    }
    else
    {
      ids = session.getAttribute("ids").toString()
    }

    if( ids == null || ids.trim().length() == 0 )
    {
      flash.message = "Error! Ids parameter is mandatory, Please Enter some ids."
      redirect(action:"index")
    }else {
      if( from == null || from.toString().equalsIgnoreCase("NULL") )
      {
        flash.message = "Error! From parameter is mandatory."
        redirect(action:"index")
      } else {
        if( StrTo == null )
        {
          flash.message = "Error! To parameter is mandatory, Please select at least one."
          redirect(action:"index")
        }
      }
    }

    def to = []

    if( StrTo instanceof String )
    {
       to.add StrTo.trim()
    }else
    {
       StrTo.each {String s ->
           to.add s.trim()
        }

    }

    // prepare the list of ids : Start
    def list = []
    ids.split("\n").each {String s ->
      list.add s.trim()
    }
    // prepare the list of ids : End

    if(params?.format && params.format != "html") //Export
       {

         println "======== In Upload =============";
         //call the service to conver the data
         Collection<Map<Compound,?>> transform =  convertService.convert(from, to, list)

         params.put("to",to);
         dataExportService.exportMassLookUp(transform,response,params) 

       }else
       {
          if( params.offset == null || params.offset.toString().equals("0"))
          {
              params.put("offset",0);
          }else
          {
             params.put("offset",Long.parseLong("0"+ params.offset.toString()) );
          }

          if( params.max == null || params.max.toString().equals("0"))
          {
              params.put("max",10);
          }else
          {
            params.put("max",Long.parseLong("0"+ params.max.toString()));
          }

          //call the service to to get Count of the data
          Long total = 0;
          if(params.total == null || params.total.toString().equals("0"))
          {
            total =  convertService.getCount(from, to, list)
          }else
          {
            total = Long.parseLong(params.total.toString())
          }

          //call the service to conver the data
          Collection<Map<Compound,?>> result =  convertService.convert(from, to, list,params)

          return [transform:result,ids:ids,from:from,to:to,idsList:list,max:params.max,offset:params.offset,total:total]
       } 
  }

  /**
   * returns the provide formats
   */
  static List getFormats() {
    return ['xml', 'json']
  }

}
